package com.lagou.dao;

import com.lagou.io.Resources;
import com.lagou.pojo.User;
import com.lagou.sqlSession.SqlSession;
import com.lagou.sqlSession.SqlSessionFactory;
import com.lagou.sqlSession.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

/**
 * @author lubiao
 * @date 2021/4/2
 * @desc
 */
public class UserDaoImpl implements IUserDao{

    private SqlSession sqlSession;

    @Override
    public List<User> findAll() throws Exception {
        initSqlSession();
        List<User> users = sqlSession.selectList("user.selectList");
        return users;
    }

    @Override
    public User findByCondition(User user) throws Exception {
        initSqlSession();
        User user1 = sqlSession.selectOne("user.selectOne", user);
        return user1;
    }

    @Override
    public Integer addUser(User user) throws Exception{
        initSqlSession();
        Integer updateCount = sqlSession.add("user.addUser", user);
        return updateCount;
    }

    @Override
    public Integer deleteUser(User user) throws Exception{
        initSqlSession();
        Integer updateCount = sqlSession.delete("user.deleteUser", user);
        return updateCount;
    }

    @Override
    public Integer updateUser(User user) throws Exception{
        initSqlSession();
        Integer updateCount = sqlSession.update("user.updateUser", user);
        return updateCount;
    }

    /**
     * 加载核心xml配置文件以及 初始化SqlSession
     * @throws Exception
     */
    private void initSqlSession() throws Exception{
        InputStream resourceAsSteam = Resources.getResourceAsSteam("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsSteam);
        sqlSession = sqlSessionFactory.openSession();
    }
}
